<?php
/**
 * Microblogging
 *
 * A class for sending short posts to the microblogging services
 * like Twitter, Tumblr or Pownce
 *
 * You can add your own microblogging API adapters defining the xxxMBAdapter class extends MBAdapter
 * and overloading the prepare() method
 *
 * @version 2.0
 * @author martin maly <maly@maly.cz>, http://www.php-suit.com
 * @copyright (C) 2008 Martin Maly
 */

/*
 Copyright (c) 2008, Martin Maly (maly@maly.cz)
 All rights reserved.

	Redistribution and use in source and binary forms, with or without modification,
	are permitted provided that the following conditions are met:

	* Redistributions of source code must retain the above copyright notice,
	this list of conditions and the following disclaimer.
	* Redistributions in binary form must reproduce the above copyright notice,
	this list of conditions and the following disclaimer in the documentation
	and/or other materials provided with the distribution.

	THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
	AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
	THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
	PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
	BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
	OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
	OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
	OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
	WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
	ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
	OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/**
 * Version history
 *
 * 2.3
 * Drbz.cz adapter added (thanks to Ludek Podolka, http://www.drbz.cz) 
 *  
 * 2.2
 * Using SSL for Twitter
 *
 * 2.1
 * Fixed old Twitter API access
 *
 * 2.0 Reworked to factory + adapter model
 * + Teidu.cz
 * + Jaiku.com
 *
 * 1.0 First version - Twitter, Pownce, Tumblr
 */

/**
 * Adapters parent abstract class
 */

if (!defined("MB_USE_SSL")) define ("MB_USE_SSL", false, 1);

abstract class MBadapter
{
	protected $host;
	protected $ch;
	protected $post;
	protected $auth;
	protected $user;
	protected $password;
	protected $postdata;
	private $status;
	protected $use_ssl;


	/**
	 * Adapter initialization - common actions for all adapters
	 *
	 * @param string $user - username or mail (depends on API)
	 * @param string $pass - password or API key (depends on API)
	 * @param string $text - text
	 */
	public function init($user, $pass, $text)
	{
		$this->user = $user;
		$this->password = $pass;
		$this->text = $text;
		$this->status = '';
		$this->use_ssl = MB_USE_SSL;
		$this->prepare();
	}

	/**
	 * API-specific preparing operations. Adapter has to overload this method
	 */
	abstract protected function prepare();

	/**
	 * Sending information
	 */
	public function send(){
		$this->ch = curl_init();

		curl_setopt($this->ch, CURLOPT_VERBOSE, 1);
		curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($this->ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
		curl_setopt($this->ch, CURLOPT_TIMEOUT, 20);
		curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION,1);
		if ($this->post){
			curl_setopt($this->ch, CURLOPT_POST, 1);
			if ($this->postdata){
				$request = http_build_query($this->postdata);
				curl_setopt($this->ch, CURLOPT_POSTFIELDS, $request);
			}
		}
		if ($this->use_ssl) {
			curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, false);
			$this->host = str_replace('http://', 'https://', $this->host);
		}

		if ($this->auth){
			curl_setopt($this->ch, CURLOPT_USERPWD, "$this->user:$this->password");
		}
		curl_setopt($this->ch, CURLOPT_URL, $this->host);
		$this->return = curl_exec($this->ch);
		$status = curl_getinfo($this->ch, CURLINFO_HTTP_CODE);

		return ($status == '200' || $status == '201') ? true : false; //just for fun
	}

	/**
	 * get status
	 */
	public function status()
	{
		return $this->status;
	}
}


// {{{ Microblogging API adapters

class TwitterMBAdapter extends MBAdapter
{
	protected function prepare(){
		$this->post = true;
		$this->postdata = array('status' => $this->text);
		$this->auth = true;
		$this->host = 'http://twitter.com/statuses/update.xml';
	}
}

class TumblrMBAdapter extends MBAdapter
{
	protected function prepare(){
		$data = array();
		$data["email"] = $this->user;
		$data["password"] = $this->password;
		$data["generator"] = 'Microblogging API '.Microblogging::VERSION;
		$data['type'] = 'regular';
		$data['body'] = $this->text;
		$this->postdata = $data;
		$this->post = true;
		$this->auth = false;
		$this->host = 'http://www.tumblr.com/api/write';
		$this->use_ssl = false; //Tumblr can't use SSL
	}
}

class PownceMBAdapter extends MBAdapter
{
	const AppKey = '2pyn3zum59w7065j26j33vopl1jk4z8u';

	protected function prepare(){
		$text = iconv("UTF-8", "ASCII//TRANSLIT", $this->text);
		$text = str_replace("'",'',$text);

		$data = array();
		$data['note_to'] = 'public';
		$data['note_body'] = $this->text;
		$this->postdata = $data;
		$this->post = true;
		$this->auth = true;
		$this->host = 'http://api.pownce.com/2.0/send/message.xml?app_key=' . self::AppKey;
		$this->use_ssl = false; //Pownce can't use SSL

	}

}

class TeiduMBAdapter extends MBAdapter
{
	protected function prepare(){
		$data = array();
		$data['text'] = $this->text;
		$hash = md5($this->user . ':' . $this->password);
		$p = md5($hash . ':' . $this->text);
		$this->postdata = $data;
		$this->post = true;
		$this->auth = false;
		$this->host = 'http://'.$this->user.'.teidu.cz/rest?p='.$p;
		$this->use_ssl = false; //Teidu can't use SSL
	}
}

class JaikuMBAdapter extends MBAdapter
{
	protected function prepare(){
		$data = array();
		$data["method"] = 'presence.send';
		$data["user"] = $this->user;
		$data["personal_key"] = $this->password;
		$data["generated"] = 0;
		$data['icon'] = 356;
		$data['location'] = '';
		$data['message'] = $this->text;
		$this->postdata = $data;
		$this->post = true;
		$this->auth = false;
		$this->host = 'http://api.jaiku.com/json';
		$this->use_ssl = false; //Jaiku can't use SSL		
	}
}

class DrbzMBAdapter extends MBAdapter
{
        protected function prepare(){
                $data = array();
                $data['body'] = $this->text;
                $data['apiKey'] = $this->password;
                $this->postdata = $data;
                $this->post = true;
                $this->auth = false;
                $this->host = 'http://drbz.cz/api/rest/'.$this->user;
                $this->use_ssl = false; //DRBZ can't use SSL
        }
}
// }}}

class Microblogging
{

	// {{{ Other constants
	const VERSION='2.2';
	// }}}

	private $adapter;

	private function __construct($adapter)
	{
		$this->adapter = $adapter;
	}

	/**
	 * Factory method: Get the Microblogging instance
	 */
	public static function Create($type) {

		if (is_string($type)){
			$adapter = $type.'MBAdapter';
			if (class_exists($adapter)){
				return new Microblogging(new $adapter());
			} else throw new Exception('Service not implemented');
		}
	}

	/**
	 * Sends text
	 * @param string $user - username or mail (depends on API)
	 * @param string $pass - password or API key (depends on API)
	 * @param string $text - text
	 * @return boolean Success or not?
	 */
	public function send($user, $pass, $text)
	{
		$this->adapter->init($user, $pass, $text);
		return $this->adapter->send();
	}

	/**
	 * Get the status of sending (might be useful if send() returned FALSE)
	 *
	 * @return string Status code
	 */
	public function status()
	{
		return $this->adapter->status();
	}
}
?>